<script setup lang="ts">
import { ElConfigProvider,ElMessage } from 'element-plus'
import {useConfigStore} from '@/store/config'
import { storeToRefs } from 'pinia'
import { moduleStore } from './store/module'
import axios  from './utils/http'
import { adminStore } from '@/store/admin' // 导入 adminStore
import LoadingScreen from '@/components/LoadingScreen.vue' // 导入加载屏幕组件
import { ref, onMounted } from 'vue'
import CustomTitleBar from './components/common/CustomTitleBar.vue';

const module_store = moduleStore()
const admin_store = adminStore() // 初始化 adminStore
let { isFullscreen } = storeToRefs(module_store)

let config_store = useConfigStore()
let {language} = storeToRefs(config_store)

// 加载状态管理
const isLoading = ref(true)
const isAppReady = ref(false)

// 处理LoadingScreen完成事件
const handleLoadingComplete = () => {
  console.log('LoadingScreen完成，隐藏加载屏幕')
  isLoading.value = false
}
import zh from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/es/locale/lang/en'
import { useServerStore } from './store/server'
import pinia from './store/pinia'
import InstanceDiagnostic from './utils/instanceDiagnostic'
import WebsocketIo from './utils/websocket' // 导入 WebsocketIo
const lang:any = {zh,en}


// 监听按键是否打开全屏和缩小全屏
document.addEventListener('keydown', function(event) {
    // 检查是否按下了 Esc 键
    if ((event.key === 'Escape' || event.keyCode === 27)) {
        console.log('按下了 ESC 键')
        event.preventDefault();
        isFullscreen.value = false
    }

    // 检查是否按下了 F11 键
    if ((event.key === 'F11' || event.keyCode === 122)) {
        console.log('F11 键被按下');
        event.preventDefault();
    }
});


// 运行实例诊断的函数
// const runInstanceDiagnostic = async () => {
//   try {
//     console.log('🔍 开始运行实例诊断...')
//     const diagnostic = InstanceDiagnostic.getInstance()
//     const result = await diagnostic.runFullDiagnostic()
    
//     // 将结果和诊断工具实例存储到全局，方便在控制台中查看和比较
//     ;(window as any).lastDiagnosticResult = result
//     ;(window as any).instanceDiagnostic = diagnostic
    
//     console.log('✅ 实例诊断完成，结果已存储到 window.lastDiagnosticResult')
//     console.log('🔧 诊断工具已暴露到 window.instanceDiagnostic')
//     console.log('💡 提示：在多个窗口中运行后，可以使用以下命令比较结果：')
//     console.log('window.instanceDiagnostic.compareResults([result1, result2])')
//   } catch (error) {
//     console.error('❌ 实例诊断失败:', error)
//   }
// }

// 处理端口信息的函数
const handlePortsUpdate = (ports: { masterPort: number; childPort: number; websocketPort: number }) => {
  console.log('=== App.vue: 处理端口更新 ===')
  console.log('接收到的端口信息:', ports)
  
  // 验证端口信息的有效性
  if (!ports || !ports.masterPort || !ports.childPort || !ports.websocketPort) {
    console.error('App.vue: 接收到无效的端口信息:', ports)
    return
  }
  
  const serverStore = useServerStore(pinia)
  
  // 更新Pinia store中的端口配置
  serverStore.updatePorts(ports)
  serverStore.setServerStatus(true)
  
  // 更新axios实例的baseURL
  console.log('App.vue: 更新axios baseURL...')
  axios.updateAxiosBaseUrls()
  
  console.log('=== App.vue: 端口更新处理完成 ===')
  ElMessage.success(`服务器端口配置已更新: 主端口${ports.masterPort}`)
  
  // 标记应用为就绪状态
  isAppReady.value = true
  
  // 运行实例诊断
  // setTimeout(() => {
  //   runInstanceDiagnostic()
  // }, 2000) // 等待2秒让应用完全初始化
}



// 主动获取端口信息并设置监听器
if (window.electronAPI) {
  const serverStore = useServerStore(pinia)
  
  console.log('=== 前端调试：初始化端口获取 ===')
  console.log('当前进程PID:', window.electronAPI.getProcessId ? window.electronAPI.getProcessId() : 'unknown')
  console.log('初始store状态:', serverStore.ports)
  
  // 主动请求一次初始端口信息
  window.electronAPI.getServerPorts().then(ports => {
    if (ports && ports.masterPort) {
      console.log('成功获取到初始端口信息:', ports);
      handlePortsUpdate(ports);
    }
  });
  
  // 2. 注册端口更新监听器（用于后续的端口变更）
  if (window.electronAPI.onPortsUpdate) {
    window.electronAPI.onPortsUpdate((ports) => {
      console.log('通过监听器接收到端口更新:', ports)
      handlePortsUpdate(ports)
    })
    console.log('端口更新监听器已注册')
  }
  
} else {
  console.warn('electronAPI不可用，可能不在Electron环境中运行')
  console.log('可用的electronAPI方法:', Object.keys(window.electronAPI || {}))
  
  // 如果不在Electron环境中，立即设置为就绪状态
  isAppReady.value = true
}

// 启动逻辑：移除固定超时，由LoadingScreen组件控制
const initializeApp = () => {
  console.log('initializeApp 开始执行')
  console.log('初始状态 - isLoading:', isLoading.value, 'isAppReady:', isAppReady.value)
  // LoadingScreen组件将通过emit事件来通知完成
}

onMounted(() => {
  initializeApp()
})


</script>

<template>
    <!-- 加载屏幕 -->
    <LoadingScreen v-if="isLoading" @loading-complete="handleLoadingComplete" />
    
    <!-- 自定义标题栏 -->
    <CustomTitleBar />
     
    <!-- 主应用内容 -->
    <div v-if="!isLoading">
        <el-config-provider :locale="lang[language]">
            <router-view v-slot="slot">
              <keep-alive include="Home">
                  <component :is="slot.Component" />
              </keep-alive>
            </router-view>
        </el-config-provider>

    </div>
</template>

<style>

</style>
